import request, { toPageInfo } from '@/utils/request'
import type { PageData } from '@/types'
import { omit } from 'lodash-es'
export { download, upload, default as request } from '@/utils/request'

const isPhpService = import.meta.env.VITE_APP_SERVICE_LANG === 'php'

export async function req<T = Record<string, any>>(url: string, data: Record<string, any> = {}) {
  return request<T>({
    url,
    data,
    method: 'POST',
  })
}


export async function req_put<T = Record<string, any>>(url: string, data: Record<string, any> = {}) {
  return request<T>({
    url,
    data,
    method: 'PUT',
  })
}

export async function req_get<T = Record<string, any>> (url: string, data: Record<string, any> = {}) {
  // 调用request函数进行GET请求
  // 调用request函数进行GET请求
  return request<T>({
    // 请求的URL
    url,
    // 请求的数据
    data,
    // 请求的方法
    method: 'GET',
  })
}

/**
 * 分页请求
 *
 * @param url   请求地址
 * @param data  body 参数
 * @param pageable 分页
 */
export async function req_page<T = Record<string, any>> (url: string, data: Record<string, any>, pageable?: { page: number, size: number }) {
  let res
  if (isPhpService) {
    if (pageable) data.pageinfo = toPageInfo(pageable)

    res = await request<PageData<T>>({
      url,
      method: 'POST',
      data,
    })
  } else {
    const page: Record<string, number> = pageable ? toPageInfo(pageable) : data.pageinfo

    res = await request<PageData<T>>({
      url: `${url}?${Object.entries(page).map(([key, value]) => `${key}=${value}`).join('&')}`,
      method: 'POST',
      data: omit(data, ['pageinfo']),
    })
  }
  if (res.data && typeof res.data === 'object') {
    if (res.data.items === undefined) res.data.items = res.data.list ?? []
    if (res.data.list === undefined) res.data.list = res.data.items ?? []
    if (res.data.total === undefined) res.data.total = res.data.count ?? 0
    if (res.data.count === undefined) res.data.count = res.data.total ?? 0
  }
  return res
}

export const page_req = req_page
export const get_page_req = req_page
export const get_req = req_get
export const put_req = req_put
